<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>拖拽</title>
  <style>
    .parent {
      width: 500px;
      height: 200px;
      border: 1px solid teal;
    }
    .child {
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
      border: 1px solid salmon;
      float: left;
      margin: 10px 10px;
    }
  </style>
</head>
<body>
  <div class="parent"></div>
  <div class="child" id="one" draggable="true">1</div>
  <div class="child" id="two" draggable="true">2</div>
  <div class="child" id="three" draggable="true">3</div>
  <div class="child" id="four" draggable="true">4</div>
</body>
<script>
  window.onload = function() {
    var parent = document.querySelector('.parent');
    var children = document.querySelectorAll('.child')
    children = Array.from(children);
    children.forEach(function(item, index) {
      item.ondragstart = function(event) {
        var id = item.id
        event.dataTransfer.setData('id', id);
        console.log('我开始被拖拽');
      }
      item.ondrag = function() {
        // console.log('拖拽过程中');
      }
      item.ondragend = function() {
        console.log('拖拽结束');
      }
    })
    // 进入父元素
    parent.ondragenter = function() {
      console.log('子元素进入');
    }
    parent.ondragover = function(event) {
      // console.log('子元素在父元素中移动');
      // 阻止事件默认行为
      event.preventDefault();
    }
    parent.ondrop = function(event) {
      var id = event.dataTransfer.getData('id')
      console.log(id);
      var dom = document.querySelector('#' + id);
      this.appendChild(dom);
      console.log('子元素放下');
      // 阻止事件冒泡
      event.stopPropagation();
    }
  }
</script>
</html>